package com.mysoft.gfyx.marketdevelop.service.impl;

import com.mysoft.framework.cache.api.CacheProvider;
import com.mysoft.framework.common.user.User;
import com.mysoft.framework.common.util.MappingUtil;
import com.mysoft.framework.context.api.ContextManager;
import com.mysoft.framework.core.function.authorization.AuthenticationUser;
import com.mysoft.framework.modeling.dto.OptionItem;
import com.mysoft.framework.service.AppService;
import com.mysoft.gfyx.common.rpc.opptyservice.OpptyServiceClientFactoryService;
import com.mysoft.gfyx.common.rpc.opptyservice.OpptyServiceClientService;
import com.mysoft.gfyx.common.rpc.opptyservice.dto.*;
import com.mysoft.gfyx.marketdevelop.mip.dto.BasicYcgListWithoutTotalResponseDto;
import com.mysoft.gfyx.marketdevelop.remoteService.RemoteProfitProvinceService;
import com.mysoft.gfyx.marketdevelop.remoteService.RemoteClueService;
import com.mysoft.gfyx.marketdevelop.remoteService.dto.GetProfitProvinceDataDto;
import com.mysoft.gfyx.marketdevelop.service.CommonService;
import com.mysoft.gfyx.marketdevelop.service.ProvinceAndCityService;
import com.mysoft.gfyx.marketdevelop.service.dto.ProvinceAndCityDto;
import com.mysoft.sdk.context.core.ThreadContextHolder;
import io.swagger.models.auth.In;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;


@Service
public class CommonServiceImp extends AppService implements CommonService {

    @Autowired
    private RemoteProfitProvinceService remoteProfitProvinceService;

    @Autowired
    private RemoteClueService remoteClueService;

    @Autowired
    private ProvinceAndCityService provinceAndCityService;

    @Autowired
    private OpptyServiceClientFactoryService opptyServiceClientFactoryService;

    @Autowired
    private CacheProvider cacheProvider;

    @Autowired
    private ContextManager contextManager;

    @Override
    public Date dateTimeStringToDate(String dateTimeString, String pattern) throws ParseException {
        if (pattern == null) {
            pattern = "yyyy-MM-dd HH:mm:ss";
        }
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        Date date = sdf.parse(dateTimeString);
        return date;
    }

    @Override
    public String dateToDateString(Date date) {
        String pattern = "yyyy-MM-dd";
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        return sdf.format(date);
    }

    @Override
    public String checkProvinceProfit(String provinceCode) {
        GetProfitProvinceDataDto getProfitProvinceDataDto = remoteProfitProvinceService.getProfitProvince();
        if (getProfitProvinceDataDto.getProvinceNumType().equals(RemoteProfitProvinceService.ProvinceNumType.Province.toString())) {
            //需要过滤权益
            AtomicReference<String> targetProvince = new AtomicReference<>(provinceCode);//默认有省份权益
            List<String> profitProvinceCode = new ArrayList<>();
            getProfitProvinceDataDto.getProvinceList().forEach(m -> {
                profitProvinceCode.add(m.getValue());
            });
            if (provinceCode == null) {//用户没有选择了省份
                if (profitProvinceCode.size() > 0) {
                    String provinceStr = profitProvinceCode.stream().map(String::valueOf).collect(Collectors.joining(","));
                    targetProvince.set(provinceStr);
                } else {//没有省份数量，不能返回数据
                    targetProvince.set("-1");
                }

            } else {//用户选择了省份
                if (profitProvinceCode.contains(provinceCode)) {
                    targetProvince.set(provinceCode);
                } else {
                    targetProvince.set("-1");
                }
            }

            return targetProvince.get();
        } else {//不需要过滤权益
            return provinceCode;
        }

    }

    @Override
    public String checkCityProfit(String cityCode) {
        if (cityCode == null || cityCode.equals("0")) {
            return cityCode;
        }
        AtomicReference<String> targetCity = new AtomicReference<>(cityCode);//默认有省份权益
        GetProfitProvinceDataDto getProfitProvinceDataDto = remoteProfitProvinceService.getProfitProvince();
        if (getProfitProvinceDataDto.getProvinceNumType().equals(RemoteProfitProvinceService.ProvinceNumType.Province.toString())) {
            List<String> profitProvinceCode = new ArrayList<>();
            getProfitProvinceDataDto.getProvinceList().forEach(m -> {
                profitProvinceCode.add(m.getValue());
            });

            List<String> profitCityCode = new ArrayList<>();
            List<ProvinceAndCityDto> cityList = provinceAndCityService.getCityAndProvinceCode(profitProvinceCode);
            cityList.forEach(n -> {
                profitCityCode.add(n.getItemCode());
            });
            if (profitCityCode.contains(cityCode)) {
                targetCity.set(cityCode);
            } else {
                targetCity.set("-1");
            }
        }
        return targetCity.get();
    }


    //
    public String checkAreaProfit(String userSelectArea) {
        if (userSelectArea == null || userSelectArea.equals("")) {
            return userSelectArea;
        }
        String[] userSelectAreaArr = userSelectArea.split(",");
        HashSet<String> userSelectAreaSet = new HashSet<>(Arrays.asList(userSelectAreaArr));

        List<OptionItem> areas = remoteClueService.getProfitProvinceAndCity();


        StringBuilder result = new StringBuilder();
        for (OptionItem area : areas) {
            if (userSelectAreaSet.contains(area.getValue())) {
                if (!result.toString().equals("")) {
                    result.append(",");
                }
                result.append(area.getValue());
            }
        }

        return result.toString();
    }

    private boolean isDataSourceContain(String value) {
        for (CommonService.BigDataType c : CommonService.BigDataType.values()) {
            if (c.name().equals(value)) {
                return true;
            }
        }
        return false;
    }

    public String getOpptyStatus(String dataSource, String dataSourceId, boolean isDetailPage) {
        if (!isDataSourceContain(dataSource) || dataSourceId.equals("")) {
            return "";
        }
        OpptyServiceClientService opptyService = opptyServiceClientFactoryService.getOpptyServiceClientService();
        com.mysoft.gfyx.common.rpc.opptyservice.dto.GetOpptyStatusRequestDto requestDto = new GetOpptyStatusRequestDto();
        requestDto.setData_source(dataSource);
        requestDto.setData_source_id(dataSourceId);
        requestDto.setDetail_page(isDetailPage);
        requestDto.setFrom_device(FromDevicePc);
        GetOpptyStatusResponseDto res = opptyService.getOpptyStatus(requestDto);
        if (res.getSuccess()) {
            return res.getData().getStatus_name();
        } else {
            return "";
        }

    }

    private Integer getOpptyStatusCache(String dataSource, String dataSourceId) {
        String tenantCode = contextManager.fetchContextInfo().getTenantCode();
        User authenticationUser = ThreadContextHolder.getInstance().get(AuthenticationUser.class);
        String cacheKey = "GETOPPTYSTATUS:" + tenantCode + "_" + dataSource + "_" + dataSourceId + "_" + authenticationUser.getUserId();
        Integer value = cacheProvider.get(cacheKey);

        if (value != null) {
            return value;
        }
        cacheProvider.set(cacheKey, 1, 3);
        return value;
    }

    public Map<String, String> getOpptyStatusBatch(String dataSource, List<String> dataSourceId) {
        if (dataSourceId.size() == 0) {
            return new HashMap<>();
        }
        Map<String, String> result = new HashMap<>();
        OpptyServiceClientService opptyService = opptyServiceClientFactoryService.getOpptyServiceClientService();
        GetOpptyStatusBatchRequestDto requestDto = new GetOpptyStatusBatchRequestDto();
        requestDto.setData_source(dataSource);
        requestDto.setData_source_id(dataSourceId);
        GetOpptyStatusBatchResponseDto res = opptyService.getOpptyStatusBatch(requestDto);
        dataSourceId.forEach(r -> {
            if (res.getData() != null) {
                res.getData().forEach(m -> {
                    if (r.equals(m.getData_source_id())) {
                        result.put(r.toString(), m.getStatus_name());
                    }
                });
            }
        });
        return result;
    }


    public boolean updateOpptyStatus(String dataSource, String dataSourceId, int status) {
        if (!isDataSourceContain(dataSource)) {
            return false;
        }
        if (dataSource.equals(BigDataType.BUILDING.name()) && dataSourceId.contains("_")) {
            String[] arr = dataSourceId.split("_");
            if (arr.length > 0) {
                dataSourceId = arr[0];
            }
        }
        OpptyServiceClientService opptyService = opptyServiceClientFactoryService.getOpptyServiceClientService();
        UpdateOpptyStatusRequestDto requestDto = new UpdateOpptyStatusRequestDto();
        requestDto.setData_source(dataSource);
        requestDto.setData_source_id(dataSourceId);
        requestDto.setStatus(status);
        requestDto.setFrom_device(FromDevicePc);
        UpdateOpptyStatusResponseDto res = opptyService.updateOpptyStatus(requestDto);
        if (res.getSuccess()) {
            return true;
        } else {
            return false;
        }
    }
}